#pragma once

#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <vector>
#include <functional>
#include "ThreadPool.hpp"
#include "InetAddr.hpp"
#include "LockGuard.hpp"

using task_t = std::function<void()>;

class MessageRoute
{
private:
    bool IsExists(const InetAddr &addr)
    {
        for (auto user : _online_user)
        {
            if (user == addr)
                return true;
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    void AddUser(InetAddr &addr)
    {
        LockGuard lock(&_mutex);
        if (!IsExists(addr))
        {
            _online_user.push_back(addr);
        }
    }

    void DelUser(InetAddr &addr)
    {
        LockGuard lock(&_mutex);
        for (auto it = _online_user.begin(); it != _online_user.end(); it++)
        {
            if (*it == addr)
            {
                _online_user.erase(it);
                break;
            }
        }
        return;
    }

    void RouteHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard lock(&_mutex);
        // 进行消息转发
        for (auto user : _online_user)
        {
            std::string send_message = "\n[" + who.Ip() + ":" + std::to_string(who.Port()) + "]#" + message + '\n';
            struct sockaddr_in clientaddr = user.Addr();
            sendto(sockfd, send_message.c_str(), send_message.size(), 0, (sockaddr *)&clientaddr, sizeof(clientaddr));
        }
        LOG(DEBUG, "forward complete\n");
    }

    void Route(int sockfd, std::string message, InetAddr who)
    {
        AddUser(who);

        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        // 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(
            &MessageRoute::RouteHelper, this, sockfd, message, who);
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};
